package com.guangfeng.yql.comm.netty.handler;

import com.guangfeng.yql.comm.netty.cv.JavaCVParseUtils;
import com.guangfeng.yql.comm.util.UriUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@ChannelHandler.Sharable
public class HttpHandler extends SimpleChannelInboundHandler<DefaultHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DefaultHttpRequest request) throws Exception {
        sendFlvReqHeader(ctx);
        FFmpegFrameGrabber pull = JavaCVParseUtils.createPull(UriUtils.getProperty(request.uri(), "url"));
    }


    private void sendFlvReqHeader(ChannelHandlerContext ctx) {
        HttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        rsp.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE)
                .set(HttpHeaderNames.CONTENT_TYPE, "video/x-flv")
                .set(HttpHeaderNames.ACCEPT_RANGES, "bytes")
                .set(HttpHeaderNames.PRAGMA, "no-cache")
                .set(HttpHeaderNames.CACHE_CONTROL, "no-cache")
                .set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED)
                .set(HttpHeaderNames.SERVER, "Yql");
        ctx.writeAndFlush(rsp);
    }
}
